﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using ServiceStack.Logging;
using g42.Dto;
using g42.Entities;
using g42.MapEntitiesDto;

namespace g42.Repos
{
  public class SampleRepository
  {
    ILog log;

    public SampleRepository()
    {
      log = LogManager.GetLogger(GetType());
    }

    public Sample Store(Sample dto)
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (var transaction = session.BeginTransaction())
          {
            SampleEnt ent = dto.ToSampleEnt();
            session.SaveOrUpdate(ent); // die Id kommt beim Speichern zurück
            transaction.Commit();
            dto.Id = ent.Id;
            return dto;
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Could not store Sample: " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }
    }

    public Sample Get()
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (session.BeginTransaction())
          {
            // Entity-Objekt lesen
            var SampleList =
              (from s in session.Query<SampleEnt>()
               select s);
            // Einfach den ersten nehmen
            SampleEnt Sample = SampleList.First();
            // Entity-Objekt in DTO transformieren
            return Sample.ToSample();
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Error MandantRepository.Get(): " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }
    }

  }

  /*
  public class CategoryRepository
  {
    public CategoryCollectionResponse Fetch(CategoryQueryCollectionRequest request)
    {
      
      base.FixupLimitAndPagingOnRequest(request);

      var totalItemCount = 0;
      var entities = base.Fetch(request.Sort, request.Include, request.Filter,
                                request.Relations, request.Select, request.PageNumber,
                                request.PageSize, request.Limit, out totalItemCount);
        
      var response = new CategoryCollectionResponse(entities.ToDtoCollection(), request.PageNumber,
                                                    request.PageSize, totalItemCount);
      return response;
    }
  }
   */
}
